package com.wisewin.pose.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.wisewin.pose.util.env.Env;
import org.apache.commons.lang.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class OSSUtils {

    private static String endpoint = Env.getProperty("endpoint");
    // accessKeyId和accessKeySecret是OSS的访问密钥，您可以在控制台上创建和查看，
    // 创建和查看访问密钥的链接地址是：https://ak-console.aliyun.com/#/。
    // 注意：accessKeyId和accessKeySecret前后都没有空格，从控制台复制时请检查并去除多余的空格。
    private static String accessKeyId = Env.getProperty("accessKeyId");
    private static String accessKeySecret = Env.getProperty("accessKeySecret");
    private static String bucketName = Env.getProperty("bucketName");


    public static String uploadFileImage(String imageData, int orgId){
        // 创建OSSClient实例
        imageData = imageData.replaceAll("data:image/png;base64,", "");
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String imageUrl = "actions/" + orgId + "/explainImage/" + UUIDUtils.UUIDGenerator() + getImageBase64Format(imageData) ;
        try {
            ossClient.putObject(bucketName, imageUrl, new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(imageData)));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ossClient.shutdown();
        }
        return getURL(imageUrl);
    }

    // 上传文件
    public static String uploadFile(String fileName, InputStream inputStream, String fileType) {
        String uploadTime = DateUtil.getDateToStr(new Date(), "yyyyMMdd");
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        fileName = fileType + "/" + uploadTime + "/" + UUIDUtils.UUIDGenerator() + getFileSuffix(fileName) ;
        ossClient.putObject(bucketName, fileName , inputStream);
        return getURL(fileName) ;
    }


    /**
     * OSS上传视频文件
     */
    public static String updloadActionsVideo( String fileName , InputStream inputStream , int orgId) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        fileName = "actions/" + orgId + "/" + UUIDUtils.UUIDGenerator() + getFileSuffix(fileName) ;
        ossClient.putObject(bucketName, fileName , inputStream);
        return getURL(fileName) ;
    }

    /**
     * OSS上传视频的封面图
     */
    public static String updloadActionsCoverImage( String fileName , InputStream inputStream , int orgId) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        fileName = "actions/" + orgId + "/coverImage/" + UUIDUtils.UUIDGenerator() + getFileSuffix(fileName) ;
        ossClient.putObject(bucketName, fileName , inputStream);
        return getURL(fileName) ;
    }

    /**
     * OSS上传画钟测试图片
     */
    public static String updloadClockPicture( String fileName , InputStream inputStream , int orgId) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        fileName = "clockTest/" + orgId + "/" + UUIDUtils.UUIDGenerator() + getFileSuffix(fileName) ;
        ossClient.putObject(bucketName, fileName , inputStream);
        return getURL(fileName) ;
    }


    public static String updloadLogoPicture(String fileName , InputStream inputStream , int orgId) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        fileName = "logo/" + orgId + "/" + UUIDUtils.UUIDGenerator() + getFileSuffix(fileName) ;
        ossClient.putObject(bucketName, fileName , inputStream);
        return getURL(fileName) ;
    }


    public static String uploadCodePic(ByteArrayInputStream byteArrayInputStream,String dir) {
        String fileName = getFileName(UUID.randomUUID().toString()+".png", dir);
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName,byteArrayInputStream);
        ossClient.putObject(putObjectRequest);
        ossClient.shutdown();
        return getURL(fileName);
    }

    private static String getFileName(String fileName, String dir) {
        String uploadDate = DateUtil.formatDate(new Date(), "yyyy-MM-dd");
        String uuid = dir + "/" + uploadDate + "/" + UUID.randomUUID().toString().replaceAll("-", "");
        return uuid + fileName;
    }

    public static String getURL(String filename) {
        return "https://" + bucketName + "." + Env.getProperty("endpointWithOutHead") + "/" + filename ;
    }

    /**
     * 获取封面图路径
     * @param filePath 文件绝对路径(包含文件名)
     * @param time 截图时间，单位毫秒ms
     * @return
     */
    public static String getCoverURL(String filePath , int time){
        return filePath + "?x-oss-process=video/snapshot,t_" + time + ",f_jpg";
    }

    /**
     * 获取文件的后缀名
     * @param fileName
     * @return
     */
    public static String getFileSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    public static void main(String[] args){
        String fileUrl = "D:\\weixinxiazai\\WeChat Files\\wxid_x24hi29wf06t12\\FileStorage\\File\\2023-03\\mirror.apk";
        String imageUrl = "softUpdate/202210/20230321182332/1666261412707.apk";
        uploadFile(fileUrl, bucketName, imageUrl);
        /*String imageData = "data:image/png;base64," + encodeBase64File("C:\\Users\\Administrator\\Pictures\\Feedback\\icon4.jpg").replaceAll("\r\n", "");
        System.out.println(imageData);
        System.out.println(uploadFileImage(imageData.replaceAll("data:image/png;base64,", ""), 1));*/
    }

    public static void uploadFile(String fileUrl, String bucketName, String imageUrl){
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            File file = new File(fileUrl);
            ossClient.putObject(bucketName, imageUrl, file);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 关闭client
            ossClient.shutdown();
        }
    }

    public static String encodeBase64File(String path)  {
        try{
            File file = new File(path);
            FileInputStream inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            inputFile.close();
            return new BASE64Encoder().encode(buffer);
        }catch (Exception e){
            return null;
        }
    }

    //判断图片base64字符串的文件格式
    public static String getImageBase64Format(String base64ImgData) {
        byte[] b = Base64.getDecoder().decode(base64ImgData);
        String type = "";
        if (0x424D == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = ".bmp";
        } else if (0x8950 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = ".png";
        } else if (0xFFD8 == ((b[0] & 0xff) << 8 | (b[1] & 0xff))) {
            type = ".jpg";
        }
        return type;
    }

    public static String netSourceToBase64(String srcUrl) {
        if(StringUtils.isEmpty(srcUrl)){
            return null;
        }
        ByteArrayOutputStream outPut = new ByteArrayOutputStream();
        byte[] data = new byte[1024 * 8];
        try {
            // 创建URL
            URL url = new URL(srcUrl);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(10 * 1000);

            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                //连接失败/链接失效/文件不存在
                return null;
            }
            InputStream inStream = conn.getInputStream();
            int len = -1;
            while (-1 != (len = inStream.read(data))) {
                outPut.write(data, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(outPut.toByteArray());
    }
}
